package com.hy.study.retry;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.Recover;
import org.springframework.retry.annotation.Retryable;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeoutException;

/**
 * 调用第三方接口，并且包含重试接口功能
 *
 * @author huyong
 * @date 2024 年 01 月 09 日 17:41: 31
 */
@Slf4j
@Service
public class AsyncThirdPartyService {

    @Autowired
    private RestTemplate restTemplate;
    private final static String URL = "http://10.216.37.229:10002/api/v1/organizations/hierarchy/management/all";

    /**
     * 当发生RestClientException.class, TimeoutException.class 异常时开始重试，重试3次，每次重试间隔为1000毫秒 第二次重试时间是第一次的2倍
     *
     * @return
     */
    @Retryable(value = {RestClientException.class, TimeoutException.class}, maxAttempts = 3, backoff = @Backoff(delay = 1000, multiplier = 2))
    public CompletableFuture<String> callAsyncCsb() {
        CompletableFuture.supplyAsync(() -> {
            ResponseEntity<String> forEntity = restTemplate.getForEntity(URL, String.class);
            return forEntity.toString();
        });
        return null;
    }

    /**
     * 当调用这个接口失败重试也失败后，使用降级处理方式
     *
     * @return
     */
    @Recover
    public CompletableFuture<String> fallback() {
        CompletableFuture.supplyAsync(() -> {
            return "重试失败";
        });
        log.info("调用接口失败开始降级处理");
        return null;
    }
}
